//
// Created by Administrator on 2022/1/26.
//

#ifndef CPP_LEARNING_LEETCODE151_H
#define CPP_LEARNING_LEETCODE151_H
#include <vector>
using namespace std;
#include <math.h>
#include <iostream>
class Solution151 {
public:
    // [l, r]
    void reverseWordsRange(string& s, int l, int r){
        while (l<r){
            char tmp = s[l];
            s[l] = s[r];
            s[r] = tmp;
            l++;
            r--;
        }
    }

    string reverseWords(string or_s) {
        int first = 0;
        int last = or_s.size();
        for(int i=0; i<or_s.size(); i++){
            if(or_s[i] != ' '){
                first = i;
                break;
            }
        }

        for(int i=or_s.size()-1; i>=0; i--){
            if(or_s[i] != ' '){
                last = i+1;
                break;
            }
        }

        string s = "";
        for(int i=first; i<last; i++){
            if(or_s[i] == ' ' && (i+1 < last) && or_s[i+1] ==' '){
                continue;
            }else{
                s += or_s[i];
            }
        }

        reverseWordsRange(s,0, s.size()-1);
        int l = 0;
        int r = 0;
        for(int i=0; i < s.size(); i++){
            if(s[i] == ' '){
                r = i-1;
                reverseWordsRange(s, l, r);
                l = i+1;
            }
            else if(i == s.size()-1){
                reverseWordsRange(s,l,i);
            }
        }
        return s;
    }
};

void test151(){
    Solution151 s;
    string str = s.reverseWords( " the sky    is blue ");
    cout<<str<<endl;
}

#endif //CPP_LEARNING_LEETCODE977_H
